<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Wiki</title>
<script type="text/javascript" src="file:///android_asset/creole.js"></script>
<script type="text/javascript" src="file:///android_asset/markdown.js"></script>
<script type="text/javascript" src="file:///android_asset/textile.js"></script>
</head>
<body>
<select id="markup">
	<option value="plain">Plain text</option>
	<option value="markdown">Markdown</option>
	<option value="creole">Creole</option>
	<!--<option value="rest">reStructuredText</option>-->
	<option value="textile">Textile</option>
</select>
<a id="home" href="">Wiki Home</a>
<div id="wiki"></div>
<pre id="wiki_plain"></pre>
<script language="javascript">
	var data = bitbeaker.getData();
	var markup = document.getElementById("markup");
	markup.addEventListener('change', changeMarkup, false);

	var div = document.getElementById('wiki');
	var pre = document.getElementById('wiki_plain');

	document.getElementById('home').href = bitbeaker.getWikiHomeUrl();

	// called from WikiActivity when page has finished loading
	function updateDropdownMenu() {
		var tmp = bitbeaker.getMarkup();
		if (tmp == "markdown" || tmp == "creole" /*|| tmp == "rest" */|| tmp == "textile")
			markup.value = tmp;
		else markup.value = "plain";

		// trigger change event manually, http://stackoverflow.com/a/2856602/262462
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent("change", false, true);
		markup.dispatchEvent(evt);
	}

	function changeMarkup() {
		if (markup.value == "plain") {
			pre.innerHTML = data;
			div.innerHTML = "";
		}
		else if (markup.value == "markdown") {
			pre.innerHTML = "";
			div.innerHTML = markdown.toHTML(data);
			fixLinks();
		}
		else if (markup.value == "creole") {
			pre.innerHTML = "";
			div.innerHTML = "";
			var creole = new Parse.Simple.Creole();
			creole.parse(div, data);
			fixLinks();
		}
		/*else if (markup.value == "rest") {
			//TODO
		}*/
		else if (markup.value == "textile") {
			pre.innerHTML = "";
			div.innerHTML = textile(data);
			fixLinks();
		}
	}

	function fixLinks() {
		var links = div.getElementsByTagName("a");
		for (i=0; i<links.length; i++) {
			// add prefix to local URLs (not starting with "http")
			// but leave anchor links as is
			if (links[i].href.substring(0,4) != "http" &&
				links[i].href.substring(0,32) != "file:///android_asset/wiki.html#") {
					links[i].href = bitbeaker.getWikiHomeUrl() + links[i].href.replace("file:///android_asset/","");
			}
			if (links[i].href.substring(0,25) == "https://bitbucket.org/api") {
				links[i].href = links[i].href.replace(/%20/g,"_");
			}
		}
	}
</script>
</body>
</html>